﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Edit_F4LocalTroubles : Form
    {
        public int troubleID;
        private List<string> serialList;
        private List<string> selectedSerial;        
        public frm_Edit_F4LocalTroubles()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            serialList = new List<string>();
            selectedSerial = new List<string>();            
            this.troubleID = 0;
            this.addDate.EditValue = DateTime.Now.Date;
            getCheckerList();
            this.staffID.Properties.AutoComplete = true;   
        }

        //////////////////////////////////////////////
        /// Load Data to form
        //////////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;
            string timeplan = null;
            string current_serial = null;
            try
            {                
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT [231_F4Troubles].ID, [231_F4Troubles].Date, [231_F4Troubles].TimePlanNo,"
                    + " [231_TimePlan].CompID, [231_F4Troubles].SerialNo, [231_TimePlan].Quantity,"
                    + " [231_F4Troubles].Quantity, [231_F4Troubles].Checker, [222_Staff].GroupID,"
                    + " [231_F4Troubles].F4TroubleContent, [231_F4Troubles].Reason, [231_F4Troubles].Solution, [231_F4Troubles].Remark"
                    + " FROM [231_F4Troubles] LEFT OUTER JOIN"
                    + " [231_TimePlan] ON [231_TimePlan].TimePlanNo=[231_F4Troubles].TimePlanNo LEFT OUTER JOIN"
                    + " [222_Staff] ON [222_Staff].StaffID=[231_F4Troubles].Checker"
                    + " WHERE [231_F4Troubles].ID=" + troubleID + ""
                    + " ORDER BY [231_F4Troubles].Date";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    this.addDate.EditValue = DateTime.Parse(dataReader["Date"].ToString()).Date;
                    this.orderNo.Text = dataReader["TimePlanNo"].ToString();
                    this.partNo.Text = dataReader["CompID"].ToString();
                    
                    timeplan = dataReader["TimePlanNo"].ToString();
                    
                    if (dataReader["SerialNo"] != DBNull.Value)
                    {
                        current_serial = dataReader["SerialNo"].ToString();
                    }

                    for (int i = 0; i < this.staffID.Properties.Items.Count; i++)
                    {
                        ComboboxItem item = new ComboboxItem();
                        item = (ComboboxItem)this.staffID.Properties.Items[i];
                        if (item.Value.ToString() == dataReader["Checker"].ToString())
                        {
                            this.staffID.SelectedIndex = i;
                        }
                    }
                    this.troubleContent.Text = dataReader["F4TroubleContent"].ToString();
                    this.troubleReason.Text = dataReader["Reason"].ToString();
                    this.solutionText.Text = dataReader["Solution"].ToString();
                    this.noteText.Text = dataReader["Remark"].ToString();
                }

                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();

                getSerialList(timeplan);
                
                serialNo.DataSource = null;
                selectedSerialNo.DataSource = null;

                string[] serial_array = current_serial.Split(',');
                for (int i = 0; i < serial_array.Length; i++)
                {
                    if (!string.IsNullOrEmpty(serial_array[i].Trim()))
                    {
                        selectedSerial.Add(serial_array[i].Trim());
                        serialList.Remove(serial_array[i].Trim());
                    }
                }
                serialNo.DataSource = serialList;
                selectedSerialNo.DataSource = selectedSerial;

                //this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                ret = false;
                MessageBox.Show(ex.Message);
                //MessageBox.Show("Cannot get data for selected trouble");
            }

            return ret;
        }

        ////////////////////////////////////////////////
        /// Load Staff list to Checker combobox
        ////////////////////////////////////////////////
        private void getCheckerList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName"
                    + " FROM [222_Staff] WHERE StopDate IS NULL ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffName"].ToString() + " | " + dataReader["StaffID"].ToString();
                    item.Value = dataReader["StaffID"].ToString();
                    this.staffID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Checker list");
            }
        } 

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            string serial = null;
            int trouble_quantity = 0;
            int total_quantity = 0;
            string checker = null;
            string trouble = null;
            string reason = null;
            string solution = null;
            string remark = null;

            ComboboxItem item = new ComboboxItem();

            if (string.IsNullOrEmpty(error))
            {
                if (!Int32.TryParse(this.quantityValue.Text, out total_quantity))
                {
                    error = "Invalid Total Quantity";
                }
            }

            if (string.IsNullOrEmpty(error))
            {                
                trouble_quantity = selectedSerial.Count;                
            }

            if (string.IsNullOrEmpty(error))
            {
                if (trouble_quantity > total_quantity)
                {
                    error = "Trouble quantity cannot be greater than Total quantity";
                }
                else
                {
                    for (int i = 0; i < selectedSerial.Count; i++)
                    {
                        if (i == 0)
                        {
                            serial += selectedSerial[i].ToString();
                        }
                        else
                        {
                            serial += "," + selectedSerial[i].ToString();
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.staffID.SelectedIndex < 0)
                {
                    error = "Please Select Checker.";
                }
                else
                {
                    item = (ComboboxItem)this.staffID.SelectedItem;
                    checker = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {                
                trouble = this.troubleContent.Text;
                reason = this.troubleReason.Text;
                solution = this.solutionText.Text;
                remark = this.noteText.Text;

                try
                {
                    myConnection.Open();
                    string sql = "UPDATE [231_F4Troubles] SET SerialNo='" + serial + "', Quantity=" + trouble_quantity + ","
                        + " Checker='" + checker + "', F4TroubleContent='" + trouble + "', Reason='" + reason + "',"
                        + " Solution='" + solution + "', Remark='" + remark + "'"
                        + " WHERE ID=" + troubleID;
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);                    
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("F4 Local Trouble updated success.");
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot update F4 Local Trouble. Please try again.");
                }                 
            }
            else
            {
                MessageBox.Show(error);
            }
        }
        
        /////////////////////////////////////////////////
        /// Create Serial No List with selected Order No
        /////////////////////////////////////////////////
        private void getSerialList(string timeplanno)
        {
            serialList.Clear();
            serialNo.DataSource = null;
            selectedSerial.Clear();
            selectedSerialNo.DataSource = null;
            this.serialNo.Enabled = true;
            this.selectedSerialNo.Enabled = true;
            this.buttonSelectAll.Enabled = true;
            this.buttonSelect.Enabled = true;
            this.buttonDeselect.Enabled = true;
            this.buttonDeselectAll.Enabled = true;
            this.troubleQty.Enabled = false;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SerialNo FROM [231_RobotOrderDetail] WHERE OrderNo='" + timeplanno + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    serialList.Add(dataReader["SerialNo"].ToString());
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();

                serialNo.DataSource = serialList;
                quantityValue.Text = serialList.Count.ToString();
                troubleQty.Text = "0";
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
            }
        }

        ////////////////////////////
        /// Select All Serial
        ////////////////////////////
        private void buttonSelectAll_Click(object sender, EventArgs e)
        {            
            foreach (string value in serialList)
            {
                selectedSerial.Add(value);
            }
            //selectedSerial = serialList;
            selectedSerialNo.DataSource = null;
            selectedSerial.Sort();
            selectedSerialNo.DataSource = selectedSerial;

            serialList.Clear();
            serialNo.DataSource = null;

            //this.quantityValue.Text = this.serialList.Count.ToString();
            this.troubleQty.Text = this.selectedSerial.Count.ToString();
        }

        /////////////////////////////////////
        /// Deselect all serial
        ////////////////////////////////////
        private void buttonDeselectAll_Click(object sender, EventArgs e)
        {
            foreach (string value in selectedSerial)
            {
                serialList.Add(value);
            }
            //selectedSerial = serialList;
            serialNo.DataSource = null;
            serialList.Sort();
            serialNo.DataSource = serialList;

            selectedSerial.Clear();
            selectedSerialNo.DataSource = null;

            //this.quantityValue.Text = this.serialList.Count.ToString();
            this.troubleQty.Text = this.selectedSerial.Count.ToString();
        }
        
        /////////////////////////////
        /// Select some serial
        /////////////////////////////
        
        private void buttonSelect_Click(object sender, EventArgs e)
        {
            if (serialNo.SelectedItems.Count > 0)
            {
                for (int i = 0; i < serialNo.SelectedItems.Count; i++)
                {
                    selectedSerial.Add(serialNo.SelectedItems[i].ToString());                    
                }
                for (int i = serialNo.SelectedItems.Count - 1; i >= 0 ; i--)
                {                    
                    serialList.Remove(serialNo.SelectedItems[i].ToString());
                }
                serialNo.DataSource = null;
                serialList.Sort();
                serialNo.DataSource = serialList;
                selectedSerialNo.DataSource = null;
                selectedSerial.Sort();
                selectedSerialNo.DataSource = selectedSerial;

                //this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();
            }            
        }

        /////////////////////////////
        /// Deselect some serial
        /////////////////////////////
        private void buttonDeselect_Click(object sender, EventArgs e)
        {
            if (selectedSerialNo.SelectedItems.Count > 0)
            {
                for (int i = 0; i < selectedSerialNo.SelectedItems.Count; i++)
                {
                    serialList.Add(selectedSerialNo.SelectedItems[i].ToString());
                }
                for (int i = selectedSerialNo.SelectedItems.Count - 1; i >= 0; i--)
                {
                    selectedSerial.Remove(selectedSerialNo.SelectedItems[i].ToString());
                }
                serialNo.DataSource = null;
                serialList.Sort();
                serialNo.DataSource = serialList;
                selectedSerialNo.DataSource = null;
                selectedSerial.Sort();
                selectedSerialNo.DataSource = selectedSerial;

                //this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();
            }
        }
    }
}
